<?php

namespace app\command;

use app\service\SeckillService;
use think\Cache;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class StockSync extends Command
{
    protected function configure()
    {
        $this->setName('stock:sync')->setDescription('同步Redis库存到数据库');
    }

    protected function execute(Input $input, Output $output)
    {
//       $redis = Cache::store('redis')->handler();
       $goodsIds = Db::name('goods')->column('id');

       foreach ($goodsIds as $goodsId){
//           $stockKey = "stock:goods:{$goodsId}";
//           $stock = $redis->get($stockKey);
           // 减少 Redis 访问
           $stock = SeckillService::getStock($goodsId);

           if($stock !== false){
               Db::name('goods')
                   ->where('id', $goodsId)
                   ->update(['seckill_stock' => $stock]);

               $output->writeln("商品 {$goodsId} 库存同步成功: {$stock}");
           }

           $output->writeln('库存同步完成');
       }
    }
}